<?php

ini_set('display_errors', 1);
ini_set('memory_limit', -1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\cache\wiki\TopicWiki as cTopicWiki;
use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\model\wiki\Wiki as mWiki;
use Doraemon\cache\PhotoCounter;
use Biz\model\brand\Brand as mBrand;
use Doraemon\model\Category as mCategory;
use Doraemon\model\Photos as mPhotos;


$topicId = 1199;
$path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'topicWiki' . DIRECTORY_SEPARATOR;

downWikiImg($topicId, $path);//生成wiki图片;

$data = getTopicWikiData($topicId, $path);//获取数据

exportData($data, $topicId);//导出excel

function getTopicWikiData($topicId, $path)
{
    $data = [];
    $wikiIds = cTopicWiki::getAllWikiIds($topicId);
    $wikiIds = [15, 16];

    $wikiList = mWiki::selectByWhere(['id' => $wikiIds], ['id', 'title', 'basic_id', 'brand_id', 'second_category_id']);
    $brandIds = array_column($wikiList, 'brand_id');
    $brandIds = array_filter(array_unique($brandIds));
    $brandList = mBrand::selectByWhere(['id' => $brandIds], ['id', 'brand_name']);
    $brandList = array_column($brandList, null, 'id');

    $cateIds = array_column($wikiList, 'second_category_id');
    $cateIds = array_filter(array_unique($cateIds));
    $cateList = mCategory::selectByWhere(['id' => $cateIds], ['id', 'cate_name']);
    $cateList = array_column($cateList, null, 'id');
    foreach ($wikiList as $row) {
        list($contentNum, $opNum) = getNoteData($row['id'], $topicId);
        $data[] = [
            'id' => $row['id'],
            'title' => $row['title'],
            'basic_id' => $row['basic_id'],
            'brand_name' => ($row['brand_id'] && isset($brandList[$row['brand_id']])) ? $brandList[$row['brand_id']]['brand_name'] : '',
            'cover_img' => $path . $row['id'],
            'category' => ($row['second_category_id'] && isset($cateList[$row['second_category_id']])) ? $cateList[$row['second_category_id']]['cate_name'] : '',
            'content_num' => $contentNum,
            'content_op_num' => $opNum,
        ];
        var_dump('商品 ID:' . $row['id']);
    }
    return $data;
}

function getNoteData($wikiId, $topicId)
{
    $opNum = 0;
    $contentNum = 0;
    $noteIds = mObjRelateWiki::getByWhere(['wiki_id' => $wikiId, 'obj_type' => mObjRelateWiki::OBJ_TYPE_NOTE], 'obj_id');
    $noteIds = array_unique($noteIds);
    foreach ($noteIds as $noteId) {
        $photoId = mPhotos::select('id', ['id' => $noteId, 'topic_activity_id' => $topicId]);
        if (!empty($photoId)) {
            $contentNum++;
            $counter = PhotoCounter::getOne($noteId);
            $opNum += ($counter['like'] + $counter['favorite']);
        }
    }
    return [$contentNum, $opNum];
}

function exportData($data, $topicId)
{
    $file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'topic-' . $topicId . '-' . date('YmdHis') . '-topicWiki.csv';
    var_dump('开始导出文件:' . $file);
    $objPHPExcel = new \PHPExcel();
    $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
    $objActSheet = $objPHPExcel->getActiveSheet();
    $objActSheet->setCellValue('A1', '商品ID');
    $objActSheet->setCellValue('B1', '商品名称');
    $objActSheet->setCellValue('C1', 'wikiID');
    $objActSheet->setCellValue('D1', '品牌名');
    $objActSheet->setCellValue('E1', '商品图');
    $objActSheet->setCellValue('F1', '二级品类');
    $objActSheet->setCellValue('G1', '商品关联该话题的内容数');
    $objActSheet->setCellValue('H1', '商品关联所有住友说的总交互数（点赞、收藏）');
    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
    $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(45);
    $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(25);//行高
    foreach ($data as $k => $v) {
        $k += 2;
        $objActSheet->getRowDimension($k)->setRowHeight(100);
        $objActSheet->setCellValue('A' . $k, $v['id']);
        $objActSheet->setCellValue('B' . $k, $v['title']);
        $objActSheet->setCellValue('C' . $k, $v['basic_id']);
        $objActSheet->setCellValue('D' . $k, $v['brand_name']);
        if ($v['cover_img']) {
            $objDrawing[$k] = new PHPExcel_Worksheet_Drawing();
            $objDrawing[$k]->setPath($v['cover_img']);
            $objDrawing[$k]->setHeight(100);
            $objDrawing[$k]->setWidth(100);
            $objDrawing[$k]->setCoordinates('E' . $k);
            $objDrawing[$k]->setOffsetX(80);
            $objDrawing[$k]->setRotation(20);
            $objDrawing[$k]->getShadow()->setVisible(true);
            $objDrawing[$k]->getShadow()->setDirection(50);
            $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());
        }
        $objActSheet->setCellValue('F' . $k, $v['category']);
        $objActSheet->setCellValue('G' . $k, $v['content_num']);
        $objActSheet->setCellValue('H' . $k, $v['content_op_num']);
    }
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save($file);
}

function downWikiImg($topicId, $path)
{
    $wikiIds = cTopicWiki::getAllWikiIds($topicId);
    $wikiIds = [15,16];
    $list = mWiki::selectByWhere(['id' => $wikiIds], ['id', 'cover_img']);
    foreach ($list as $row) {
        $filename = $path . $row['id'];
        $url = $row['cover_img'];
        if (!file_exists($filename)) {
            download($url, $filename);
        }
    }
}

function download($url, $filename)
{
    var_dump('下载wiki商品图片');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
    $file = curl_exec($ch);
    curl_close($ch);
    $resource = fopen($filename, 'a');
    fwrite($resource, $file);
    fclose($resource);
    return $filename;
}

